package jp.co.brilliantservice.app.sos;

import twitter4j.http.AccessToken;
import jp.co.brilliantservice.app.sos.TwitterAsyncTask.onRetrieveAccessTokenListener;
import jp.co.brilliantservice.app.sos.TwitterAsyncTask.onRetrieveAuthUrlListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.View;
import android.webkit.WebView;

public class SettingActivity extends PreferenceActivity {
	private AccessToken mAccessToken = null;
    private String mAuthUrl;
    private CustomDialog mDialog;
    private boolean verified = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.pref);
//        android.os.Debug.waitForDebugger();

    }
    public void onAuthButton(View view) {
		startOAuth();
    }

	private void onRetrieveAccessTokenListener(AccessToken accessToken) {
		mAccessToken = accessToken;
		if (mDialog!=null) {
			mDialog.dismiss();
		}
		if (mAccessToken!=null && !verified) {
			//トークンの書き込み
			SettingManager pref = new SettingManager(this);
	        pref.set("token",mAccessToken.getToken());
	        pref.set("tokenSecret",mAccessToken.getTokenSecret());
	        verified = true;
		}
	}

	private void startOAuth() {
		TwitterAsyncTask asyncTask = new TwitterAsyncTask(this, null, false);
        asyncTask.setOnRetrieveAuthUrlListener(new onRetrieveAuthUrlListener() {
			@Override
			public void onRetrieveAuthUrl(String authUrl) {
				mAuthUrl = authUrl;
				mDialog = new CustomDialog(SettingActivity.this);
				WebView webView = new WebView(SettingActivity.this);
				webView.loadUrl(mAuthUrl);
				mDialog.setTitle(R.string.summary_twitter);
				mDialog.setContentView(webView);
				mDialog.show();
			}
		});
        asyncTask.execute(TwitterAsyncTask.GET_OAUTH_URL);
		try {
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		Uri uri=intent.getData();
		if (uri!=null) {
			if (uri.toString().startsWith(TwitterAsyncTask.CALLBACKURL)) {
				if (verified)return;
				String verifier=uri.getQueryParameter(
						oauth.signpost.OAuth.OAUTH_VERIFIER);
				try {
					TwitterAsyncTask asyncTask = new TwitterAsyncTask(this, null,false);
			        asyncTask.setOnRetrieveAccessTokenListener(new onRetrieveAccessTokenListener() {
						@Override
						public void onRetrieveAccessToken(AccessToken accessToken) {
							onRetrieveAccessTokenListener(accessToken);
						}
			        });
			        asyncTask.execute(TwitterAsyncTask.GET_ACCESS_TOKEN, verifier);
				} catch(Exception e){
					e.printStackTrace();
					if (mDialog!=null) {
						mDialog.dismiss();
					}
				}
			} else if (uri.toString().startsWith("sosbutton://startoauth")) {
				verified = false;
				startOAuth();
			}
		}
	}

}